var httpUtil = require('../../utils/httpUtil.js');
// pages/me/me.js
Page({

  /**
   * 页面的初始数据
   */

  data: {
    hidden: false, //加载
    outline: false, //有无网络
    imgUrls: [], //轮播
    interval: 2200, //自动切换时间间隔
    autoplay: true,
    duration: 500, //滑动动画时长
    circular: true, //衔接滑动
    indicatorDots: true, //标记
    list: [],

    deviceid: '', //设备号
    phone: '',
    status1: 1,
    type: 1, //获取已选的价格
    issaoma: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.q !== undefined) {
      var scan_url = decodeURIComponent(options.q);
      this.setData({
        deviceid: '' + scan_url.substring(scan_url.length - 11, scan_url.length) + '',
        issaoma: true
      })
      wx.setStorage({
        key: 'deviceid',
        data: '' + scan_url.substring(scan_url.length - 11, scan_url.length) + '',
      })
    }else{
      this.setData({
        deviceid: 'M2019000501',
        issaoma: true
      })
      wx.setStorage({
        key: 'deviceid',
        data: 'M2019000501',
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //获取当前网络状态
    wx.getNetworkType({
      success: function(res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == 'none' || res.networkType == 'unknown') {
          that.setData({
            outline: true
          })
        } else {
          that.setData({
            outline: false,
            type: 1,
          })
          that.getToken()
        }
      }
    })

    //监听网络状态
    wx.onNetworkStatusChange(function(res) {
      if (res.networkType == 'none' || res.networkType == 'unknown') {
        that.setData({
          outline: true
        })
      } else {
        that.setData({
          outline: false,
          type: 1,
        })
        that.getToken()
      }
    })
  },

  //扫码
  scanCode: function() {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        var scan_url = res.result;
        that.setData({
          deviceid: '' + scan_url.substring(scan_url.length - 11, scan_url.length) + '',
          issaoma: true
        })
        wx.setStorage({
          key: 'deviceid',
          data: '' + scan_url.substring(scan_url.length - 11, scan_url.length) + '',
        })

      }
    })
  },
  radioChange: function(e) {
    var that = this;
    var items = that.data.list;
    for (var i = 0; i < items.length; i++) {
      if (e.detail.value == i) {
        items[i].checked = true;
      } else {
        items[i].checked = false;
      }
    }
    that.setData({
      type: e.detail.value
    })
  },
  // 获取token
  getToken: function() {
    var that = this;
    that.setData({
      hidden:true
    })
    wx.login({
      success: function(res) {
        if (res.code) {
          var req = JSON.stringify({
            code: res.code
          }, )
          //获取sessionKey
          wx.request({
            url: 'https://www.tiantong369.com/gettoken',
            data: req,
            method: "POST",
            //头信息设置
            header: {},
            success: function(res) {
              if (res.data.status == 200) {
                wx.setStorageSync("token", res.data.token);
                that.login()
                that.post()
                that.getLunbo()
              }
            },
            fail: function(res) {

            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  //获取登录信息
  login: function() {
    var that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          var req = {
            js_code: res.code,
          }
          //获取sessionKey
          wx.request({
            url: 'https://www.tiantong369.com/crm/GetWXUserInfo/',
            data: req,
            method: "POST",
            //头信息设置
            header: {
              'x-access-token': wx.getStorageSync("token")
            },
            success: function(res) {
              wx.setStorageSync("openId", res.data.openid);
              wx.setStorageSync("sessionKey", res.data.session_key);
            },
            fail: function(res) {
              wx.showToast({
                title: '获取登录信息失败，请稍后重试',
              })
              return;
            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  //获取页面信息
  getLunbo: function() {
    var that = this;
    var req = {}
    httpUtil.post("/crm/index", req)
      .then(function(res) {
        if (res.data.status == 200) {
          that.setData({
            phone: res.data.app.phone,
            imgUrls: res.data.app.banner,
          })
        }
      }).catch(function(res) {
        console.log(res);
      });
  },
  //获取页面信息
  post: function() {
    var that = this;
    var req = {
      deviceid: '' + that.data.deviceid + ''
    }
    httpUtil.post("/crm/GetEmpPrice", req)
      .then(function(res) {
        that.setData({
          list: [],
          hidden: false
        })
        if (res.data.status == 200) {
          var arr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            arr.push(res.data.data[i])
          }
          arr[1].checked = true
          that.setData({
            list: arr,
          })
        } else {
          wx.showToast({
            title: '' + res.data.err_msg + '',
            icon: 'none',
          })
        }
      }).catch(function(res) {
        console.log(res);
      });
  },
  //支付
  powerDrawer: function(e) {
    var that = this;
    if (that.data.issaoma == false) {
      wx.showToast({
        title: '未检测到设备，请点击右上角的扫一扫，选择正确的二维码扫描...',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    that.setData({
      status1: 1,
    })
    var req = {
      deviceid: '' + that.data.deviceid + '',
    }
    req = JSON.stringify(req)
    httpUtil.post("/crm/senddevicemsg", req)
      .then(function(res) {
        if (res.data.status == 200) {
          that.setData({
            hidden: true
          })
          that.startSetInter()
        } else {
          wx.showToast({
            title: '' + res.data.err_msg + '',
            icon: 'none',
            duration: 1500
          });
        }
      }).catch(function(res) {
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 1500
        });

      })
  },
  startSetInter: function() {
    var that = this;
    var req = {
      deviceid: '' + that.data.deviceid + '',
    }
    req = JSON.stringify(req)
    httpUtil.post("/crm/GetEmpPrice", req)
      .then(function(res) {
        if (res.data.device.status == 1) {
          that.pay();
        } else {
          that.data.status1++;
          if (that.data.status1 < 20) {
            setTimeout(function(){
              that.startSetInter();
            },1500)
          } else {
            that.setData({
              hidden: false,
              status1:1
            })
            wx.showToast({
              title: '设备正在联网，请5秒后扫码重试。。。',
              icon: 'none',
              duration: 2000
            })
            return;
          }
        }
      }).catch(function(res) {
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 1500
        });
      })
  },

  pay: function() {
    var that = this;
    if (that.data.list.length == 0) {
      return;
    } else {
      var req = {
        orderDes: "足疗按摩",
        DevID: '' + that.data.deviceid + '',
        total_fee: '' + that.data.list[that.data.type].price + '',
        Openid: wx.getStorageSync('openId'),
        total_time: that.data.list[that.data.type].second
      }
      req = JSON.stringify(req)
      httpUtil.post("/crm/GetTOrderInfo", req)
        .then(function(res) {
          that.setData({
            hidden: false,
          })
          //微信支付
          wx.requestPayment({
            timeStamp: res.data.timeStamp, //时间戳 当前的时间
            nonceStr: res.data.nonceStr, //随机字符串
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            //接口调用成功
            'success': function(res) {
              //打开设备
              wx.showToast({
                title: '支付成功,设备启动中。。。',
                icon: 'none',
                duration: 2000,
              })
            },
            //接口调用失败
            'fail': function(res) {
              if (res == 'requestPayment:fail cancel') {
                return;
              }
              //用户取消或支付异常
            },
            //接口调用结束
            'complete': function(res) {

            }
          })
        }).catch(function(res) {
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 1500
          })
        });
    }

  },

  //体验码打开
  code: function() {
    var that = this;
    if (that.data.issaoma == false) {
      wx.showToast({
        title: '未检测到设备，请点击右上角的扫一扫，选择正确的二维码扫描...',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/Pay/pay'
    })
  },
  goodsDetail: function (e) {
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodid=' + e.target.dataset.id
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
})